package demo2;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test3 {
    public static void main(String[] args) {
        Class<?> c1 ;
        try {
            c1 =  Class.forName("demo2.Student");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
//        //通过Class对象实例化类的对象
//        try {
//            Student s1 = (Student) c1.newInstance();   //返回的是Object类需要强转
//            System.out.println(s1);
//        } catch (InstantiationException e) {
//            throw new RuntimeException(e);
//        } catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        }
        try {
            //con获取Student的构造方法
            Constructor<Student> con = (Constructor) c1.getDeclaredConstructor(String.class  , int.class);
           //要调用私有的方法需要调整，私有的是不能调用的，用这个方法确认调用
            con.setAccessible(true);
            //用con创建Student对象
           Student s1 =  con.newInstance("李四", 10) ;
            System.out.println(s1);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
}
